package com.platform.module.user.config;

import com.platform.module.common.utils.ThreadMdcUtil;
import org.slf4j.MDC;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class CustomThreadPool {
    @Bean(name = "asyncPoolTaskExecutor")
    public Executor getAsyncTheadPoolExecutor() {
        CustomThread taskExecutor = new CustomThread();
        taskExecutor.setCorePoolSize(20);//线程池维护最少数量
        taskExecutor.setMaxPoolSize(200);//线程池维护线程的最大数量,只有在缓冲队列满了之后才会申请超过核心线程数的线程
        taskExecutor.setQueueCapacity(25);//缓存队列
        taskExecutor.setKeepAliveSeconds(200);//允许的空闲时间,当超过了核心线程出之外的线程在空闲时间到达之后会被销毁
        taskExecutor.setThreadNamePrefix("platform-module-user-system");
        //线程池对拒绝任务的处理策略：这里采用了CallerRunsPolicy策略，
        //当线程池没有处理能力的时候，该策略会直接在 execute 方法的调用线程中运行被拒绝的任务；
        //如果执行程序已关闭，则会丢弃该任务
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        taskExecutor.setAwaitTerminationSeconds(60);//等待的时间，因为不能无限的等待下去。
        taskExecutor.initialize();
        return taskExecutor;
    }

    static class CustomThread extends ThreadPoolTaskExecutor {
        public CustomThread() {
            super();
        }

        @Override
        public void execute(Runnable task) {
            super.execute(ThreadMdcUtil.wrap(task, MDC.getCopyOfContextMap()));
        }

        @Override
        public Future<?> submit(Runnable task) {
            return super.submit(ThreadMdcUtil.wrap(task, MDC.getCopyOfContextMap()));
        }

        @Override
        public <T> Future<T> submit(Callable<T> task) {
            return super.submit(ThreadMdcUtil.wrap(task, MDC.getCopyOfContextMap()));
        }
    }
}
